package com.ds.app;

import com.ds.app.database.DBModuleManager;
import com.ds.app.database.DbModule;
import com.ds.common.cache.Cache;

public class AppRoManager {
	

	private Cache moduleCache;
	
	private Cache moduleServerIDCache;

	private Cache moduleNameCache;
	
	private static AppRoManager cacheManager;
	
	public static final String THREAD_LOCK = "Thread Lock";

	// name caches

	private boolean cacheEnabled;
	
	private DBModuleManager moduleManager;

	public static AppRoManager getInstance() {
		if (cacheManager == null) {
			synchronized (THREAD_LOCK) {
				if (cacheManager == null) {
					cacheManager = new AppRoManager();
				}
			}
		}
		return cacheManager;
	}
	

	public AppRoManager() {
		this.moduleManager=DBModuleManager.getInstance();

	}

	public DbModule getModuleByID(String moduleId)
			throws ModuleNotFoundException {
		if (!cacheEnabled) {
			return moduleManager.loadModuleByKey(moduleId);
		}
		// Cache is enabled.
		DbModule module = (DbModule) moduleCache.get(moduleId);
		if (module == null) {
			module = moduleManager.loadModuleByKey(moduleId);
			moduleCache.put(moduleId, module);
			moduleNameCache.put(moduleId, module.getName());
		}
		return module;
	}
	
	
	public DbModule getModuleByServiceID(String serviceId)
			throws ModuleNotFoundException {
		if (!cacheEnabled) {
			return moduleManager.loadModuleByServiceKey(serviceId);
		}
		// Cache is enabled.
		String moduleId = (String) moduleServerIDCache.get(serviceId);
		DbModule module = null;
		if (moduleId == null) {
			module =  moduleManager.loadModuleByServiceKey(serviceId);
			moduleCache.put(moduleId, module);		
			moduleNameCache.put(moduleId, module.getName());
		}else{
			module=this.getModuleByID(moduleId);
		}
		
		moduleServerIDCache.put(serviceId, module.getID());
		return module;
	}

	public void removeModule(String moduleId) {
		if (moduleCache.containsKey(moduleId)) {
			synchronized (moduleId) {
				moduleCache.remove(moduleId);
			}
		}
	}


	
}
